package com.asia5b.a5mall.order.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.middleware.config.Asia5bPayUtils
import com.asia5b.a5mall.middleware.event.AsiaPayEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderDetailActivityVM
import com.asia5b.a5mall.middleware.model.order.OrderDetailModel
import com.asia5b.a5mall.middleware.model.bean.OrderDetailPriceBean
import com.asia5b.a5mall.middleware.model.order.OrderPayModel
import com.asia5b.a5mall.middleware.model.order.TradeType
import com.asia5b.a5mall.middleware.model.bean.MenuBean
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.OrderDetailmAdapter
import com.asia5b.a5mall.order.adapter.OrderDetailShop3Adapter
import com.asia5b.a5mall.order.adapter.OrderDetailPriceAdapter
import com.asia5b.a5mall.order.databinding.ActivityOrderdetail2Binding
import com.asia5b.a5mall.order.fragment.LogisDF
import com.asia5b.a5bmall.same.dialog.OrderCancelDialog
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.event.OrderAfterSaleEvent
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import kotlinx.android.synthetic.main.activity_orderdetail2.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/1/13.
 * @Note   订单详细
 */
@Route(path = ActCons.OrderDetail2Activity)
class OrderDetail2Activity : SimpleActivity<OrderDetailActivityVM, ActivityOrderdetail2Binding>() {
    override val viewModelClazz: Class<OrderDetailActivityVM>
        get() = OrderDetailActivityVM::class.java

    override fun getDataBinding(): ActivityOrderdetail2Binding {
        orderSn = intent.getStringExtra("orderSn") ?: ""
        return ActivityOrderdetail2Binding.inflate(layoutInflater)
    }

    override var sIsDark = true

    //订单号
    var orderSn: String = ""
    var orderDetailModel = OrderDetailModel()

    //商品列表
    val goods = arrayListOf<OrderDetailModel>()
    val goodsAdapter by lazy { OrderDetailShop3Adapter(goods, mActivity as OrderDetail2Activity) }
    val goodsRecyclerView by lazy { rv_orderdetail_goods }

    //订单价格列表
    val orderDetailPriceBeanList = arrayListOf<OrderDetailPriceBean>()
    val orderDetailPriceAdapter by lazy { OrderDetailPriceAdapter(orderDetailPriceBeanList) }
    val orderDetailPriceRecyclerView by lazy { rv_orderdetail_price }

    val actionDatas = arrayListOf<MenuBean>()
    val mAdapter = OrderDetailmAdapter(actionDatas)
    val actionRecyclerView by lazy { rv_orderdetail_action }

    override fun initView() {
        goodsRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = goodsAdapter
        }
        orderDetailPriceRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = orderDetailPriceAdapter
        }
        actionRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false)!!
            adapter = mAdapter
        }
    }

    fun setView() {
        //tv_orderdetail_expressstate 订单状态
        tv_orderdetail_expressstate.text = orderDetailModel.order_status_text_text

        //总价
        tv_orderdetail_totalprice.text = ""

        //收货人姓名 tv_orderdetail_receivename
        tv_orderdetail_receivename.text = "${orderDetailModel.ship_name} ,${orderDetailModel.ship_mobile}"
        //收货地址 tv_orderdetail_receiveaddress
        tv_orderdetail_receiveaddress.text = orderDetailModel.address

        //设置商品详情
        goods.clear()
        goods.add(orderDetailModel)
        goodsAdapter.notifyDataSetChanged()

        //订单备注
        tv_orderdetail_remark.isEnabled = false
        tv_orderdetail_remark.setText(orderDetailModel.remark)
        if (TextUtils.isEmpty(orderDetailModel.remark)) {
            tv_orderdetail_remark.setText("-")
        }

        //订单价格列表
        orderDetailPriceBeanList.clear()
        //订单编号
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_copy
            name = getString(R.string.售后单号)
            value = orderDetailModel.sn
        })
        //下单时间
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            var create_time = WTimeUtils.format("${orderDetailModel.create_time * 1000}", WTimeUtils.text_yyyy_MM_dd)
            type = OrderDetailPriceBean.item_normal
            name = getString(R.string.下单时间)
            value = create_time
        })
        //送货时间
//        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
//            type = OrderDetailPriceBean.item_normal
//            name = getString(R.string.orderdetail_delivery_time)
//            value = orderDetailModel.receive_time
//        })
        //支付方式
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_normal
            name = getString(R.string.支付方式)
            value = if (orderDetailModel.payment_num == 1) {
                getString(R.string.一次付款)
            } else {
                getString(R.string.二次付款)
            }
        })
        //运输方式
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_normal
            name = getString(R.string.运输方式)
            value = if (TextUtils.isEmpty(orderDetailModel.fast_name)) {
                "-"
            } else {
                "${orderDetailModel.fast_name}"
            }
        })
        //商品总价
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_goods_price
            name = getString(R.string.商品总价)
            value = CurrencyPriceBuilder3().run {
                price = orderDetailModel.goods_price
                priceList = orderDetailModel.goods_price_list
                buildPriceText()
            }
        })
        //国际运费
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_international_price
            name = getString(R.string.国际运费)
            value = CurrencyPriceBuilder3().run {
                price = orderDetailModel.international_price
                priceList = orderDetailModel.international_price_list
                buildPriceText()
            }
        })
        //优惠券折扣
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_coupon_price
            name = getString(R.string.优惠券折扣)
            value = CurrencyPriceBuilder3().run {
                price = orderDetailModel.coupon_price
                priceList = orderDetailModel.coupon_price_list
                buildPriceText()
            }
        })
        //订单总价
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_order_price
            name = getString(R.string.订单总价)
            value = CurrencyPriceBuilder3().run {
                price = orderDetailModel.order_price
                priceList = orderDetailModel.order_price_list
                buildPriceText()
            }
        })
        //实付金额(订单总价)
        orderDetailPriceBeanList.add(OrderDetailPriceBean().apply {
            type = OrderDetailPriceBean.item_totalprice
            name = getString(R.string.综合费用)
            value = CurrencyPriceBuilder3().run {
                price = orderDetailModel.need_pay_money
                priceList = orderDetailModel.need_pay_money_list
                buildPriceText()
            }
            tv_orderdetail_totalprice.setText(String.format(getString(R.string.需付款_数), value))

        })
        orderDetailPriceAdapter.notifyDataSetChanged()


        //设置点击事件
        actionDatas.clear()
        actionDatas.addAll(orderDetailModel.getActionList())
        mAdapter.notifyDataSetChanged()
    }

    override fun initEvent() {
        orderDetailPriceAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.tv_orderdetailprice_copy -> {
                    val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val clip = ClipData.newPlainText("Asia5B", orderDetailModel.sn)
                    cm.setPrimaryClip(clip)
                    showMessage(R.string.复制成功)
                }
            }
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val menuBean = mAdapter.getItem(position) as MenuBean
            when (menuBean.name) {
                "allow_rog" -> {//确认收货
                    CancelSureViewModel(mActivity, R.string.请收到货后再确认收货) {
                        mViewModel.rog(orderSn)
                    }.show()

                }
                "allow_pay" -> {//去付款
                    Asia5bPayUtils.getAuthorization(mActivity, true) { isCanSkip ->
                        if (isCanSkip) {
                            mViewModel.getTradeSerialNo(orderSn)
                        }
                    }

                }
                "allow_comment" -> {//评价晒单
                    push(ActCons.PostCommentActivity, {
                        it.withSerializable("data", orderDetailModel)
                    })
                }
                "check_logis" -> {//查看物流
                    LogisDF().apply {
                        this.orderDetailModel = this@OrderDetail2Activity.orderDetailModel
                    }.show(supportFragmentManager, "LogisDF")
                }
//                "allow_apply_service" -> {//申请售后,//todo 这里不应该出现申请售后按钮,因为已经是详情界面了
//                    push(ActCons.OrderAfterSaleActivity, {
//                        it.withString("orderSn", orderSn)
//                    })
//                }
                "cancel_order" -> {//取消订单
                    if (TextUtils.equals(orderDetailModel.pay_status, "PAY_YES")) {
                        push(ActCons.OrderAfterSaleActivity, {
                            it.withString("orderSn", orderDetailModel.sn)
                        })
                    } else {
                        var dialog = OrderCancelDialog(mActivity)
                        dialog.show()
                        dialog.setSureClick<String> { reson ->
                            mViewModel.cancel(orderSn, reson)
                        }
                    }
                }
            }
        }
    }

    override fun startObserver() {
        mViewModel.getOrderDetailResultLiveData.observe(this, Observer {
            getOrderDetailResult(it)
        })
        mViewModel.rogResultLiveData.observe(this, Observer {
            rogResult()
        })
        mViewModel.cancalResultLiveData.observe(this, Observer {
            cancelResult()
        })

        mViewModel.getTradeSerialNoResultLiveData.observe(this, Observer {
            getTradeSerialNoResult(it)
        })
    }

    override fun initData() {
        getOrderDetail()


    }

    fun getOrderDetail() {
        mViewModel.getOrderDetail(orderSn)
    }

    fun getOrderDetailResult(model: OrderDetailModel?) {
        if (model != null) {
            this.orderDetailModel = model!!
            setView()
        }
    }

    fun cancelResult() {
        pop()
    }

    fun rogResult() {
        pop()
    }

    var waitOrderPayModel: OrderPayModel? = null
    fun getTradeSerialNoResult(tradeSerialNo: String?) {
        tradeSerialNo?.run {
            waitOrderPayModel = OrderPayModel()
            waitOrderPayModel!!.run {
                tradeType = TradeType.Order
                sn = tradeSerialNo
                payPrice = orderDetailModel.need_pay_money
                Asia5bPayUtils.skipPay(mActivity, waitOrderPayModel!!)
            }

        }
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun paySuccess(tradeSerialNo: String?) {
        waitOrderPayModel?.let {
            if (TextUtils.equals(it.sn, tradeSerialNo)) {
                Asia5bPayUtils.checkOrderPayState(it.orderSn) {
                    if (it) {
                        getEventBus().post(AsiaPayEvent(orderDetailModel!!.sn))
                        pop()
                    }
                }.joinComposite(mCompositeDisposable)
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOrderAfterSaleEvent(event: OrderAfterSaleEvent) {
        pop()
    }


}